﻿// Our default grid options
var defaultGridOptions = {
    enableCellNavigation: true,
    enableColumnReorder: false,
    enableAddRow: false,
    editable: true,
    editOnDoubleClick: true,
    multiSelect: false,
    forceFitColumns: false,
    autoHeight: false,
    resizable: false,
    autoEdit: false,
    showHeaderRow: true,
    rowHeight: 36,
    headerHeight: 36,
    headerRowHeight: 36

};

var currentDate = new Date();
$().ready(function () {
    $('.button').button();

    var scheduleGrid = setUpScheduleGrid('#scheduleGrid');

    loadSchedule(new Date());

    $('#previousWeek').click(function () {
        var date = new Date();
        date.setFullYear(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
        date.setDate(currentDate.getDate() - 7);
        loadSchedule(date);
    });
    $('#nextWeek').click(function () {
        var date = new Date();
        date.setFullYear(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
        date.setDate(currentDate.getDate() + 7);
        loadSchedule(date);
    });

    // buttons
    $('.buttonRight').mousedown(function () {
        $(this).attr('src', '/Content/images/buttonRightClick.png');
    }).mouseup(function () {
        $(this).attr('src', '/Content/images/buttonRight.png');
    });
    $('.buttonLeft').mousedown(function () {
        $(this).attr('src', '/Content/images/buttonLeftClick.png');
    }).mouseup(function () {
        $(this).attr('src', '../Content/images/buttonLeft.png');
    });
    var startDate;
    var endDate;

    var selectCurrentWeek = function () {
        window.setTimeout(function () {
            $('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active');
        }, 1);
    };

    $('#scheduleDatePicker').datepicker({
        showOtherMonths: true,
        selectOtherMonths: true,
        onSelect: function (dateText, inst) {
            var date = $(this).datepicker('getDate');
            startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
            endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
            var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
            //$('#startDate').text($.datepicker.formatDate(dateFormat, startDate, inst.settings));
            //$('#endDate').text($.datepicker.formatDate(dateFormat, endDate, inst.settings));

            selectCurrentWeek();
            $('#scheduleDate').text(dateText);
            loadSchedule($('#scheduleDatePicker').datepicker('getDate'));
        },
        beforeShowDay: function (date) {
            var cssClass = '';
            if (date >= startDate && date <= endDate)
                cssClass = 'ui-datepicker-current-day';
            return [true, cssClass];
        },
        onChangeMonthYear: function (year, month, inst) {
            selectCurrentWeek();
        },
        dateFormat: "M d, yyyy"
    });

    $('.ui-datepicker-calendar tr').live('mousemove', function () { $(this).find('td a').addClass('ui-state-hover'); });
    $('.ui-datepicker-calendar tr').live('mouseleave', function () { $(this).find('td a').removeClass('ui-state-hover'); });

    $('#scheduleDate').click(function () {
        $('#scheduleDatePicker').datepicker('show');
    });
    $('#saveSchedule').click(function () {
        block({ element: $('#scheduleGrid'), text: 'Saving' });
        $.post('/schedulemanagement/updateschedule', { date: $.format.date(currentDate, "yyyy-MM-dd"), schedule: JSON.stringify(scheduleGrid.dataView.getItems()) },
            function () {

            }).error(function () {
                alert('Unable to save schedule!');
            }).complete(function () {
                unblock({ element: $('#scheduleGrid') });
            });
    });
    $('#reloadSchedule').click(function () {
        block({ element: $('#scheduleGrid'), text: 'Loading' });
        loadSchedule(currentDate);
    });
    $('#generateSchedule').click(function () {
        //        block({ element: $('#scheduleGrid'), text: 'Saving' });

        var date = new Date();
        date.setFullYear(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
        date.setDate(currentDate.getDate() - 7);
        loadSchedule(date,true);

        //        $.post('/schedulemanagement/generateschedule', { date: $.format.date(currentDate, "yyyy-MM-dd") }, function () {

        //        }).error(function () {
        //            alert('Unable to save schedule!');
        //        }).complete(function () {
        //            unblock({ element: $('#scheduleGrid') });
        //        });
    });
    function loadSchedule(date, preserveCurrentDate) {

        if (date !== undefined) {
            block({ element: $('#scheduleGrid'), text: 'Loading' });
            // Retrieve schedule from server
            $.get('/schedulemanagement/GetSchedule', { date: $.format.date(date, "yyyy-MM-dd") },
                function (response) {
                    if (response.Result) {
                        // Load schedule data into grid
                        // Display schedule date
                        scheduleGrid.dataView.setItems(response.Data.Schedules);
                        scheduleGrid.invalidate();
                        if (!preserveCurrentDate) {
                            currentDate = new Date(response.Data.Date.replace( /-/ , "/"));
                            $('#scheduleDate').text($.format.date(currentDate, "MMMM d, yyyy"));
                        }
                    } else {
                        alert('Unable to retrieve schedule: ' + response.Data);
                    }
                }).complete(function () {
                    unblock({ element: $('#scheduleGrid') });
                });
        }
    }


});



// Sets up the sample grid
function setUpScheduleGrid($gridSelector) {
    // First, define the grid's columns
    var columns = [
        { id: "Employee", name: "Employee", field: "Employee", width: 250, sortable: true },
        { id: "Monday", name: "Monday", field: "Monday", width: 100, sortable: true, editor: TimeEditor, formatter: hoursFormatter, cssClass: "hours" },
        { id: "Tuesday", name: "Tuesday", field: "Tuesday", width: 100, sortable: true, editor: TimeEditor, formatter: hoursFormatter, cssClass: "hours" },
        { id: "Wednesday", name: "Wednesday", field: "Wednesday", width: 100, sortable: true, editor: TimeEditor, formatter: hoursFormatter, cssClass: "hours" },
        { id: "Thursday", name: "Thursday", field: "Thursday", width: 100, sortable: true, editor: TimeEditor, formatter: hoursFormatter, cssClass: "hours" },
        { id: "Friday", name: "Friday", field: "Friday", width: 100, sortable: true, editor: TimeEditor, formatter: hoursFormatter, cssClass: "hours" },
        { id: "Saturday", name: "Saturday", field: "Saturday", width: 100, sortable: true, editor: TimeEditor, formatter: hoursFormatter, cssClass: "hours" },
        { id: "Sunday", name: "Sunday", field: "Sunday", width: 100, sortable: true, editor: TimeEditor, formatter: hoursFormatter, cssClass: "hours" }
    ];
    function hoursFormatter(row, cell, value) {
        return "<div><p>" + (value ? value : "N/A") + "</p></div>";
    }
    function timeValidator() {
        debugger;
    }
    // Set some additional options
    var options = $.extend(true, {}, defaultGridOptions);
    options.hasHeaderFilters = true;

    // Create the grid
    var grid = new Slick.Grid($gridSelector, [], columns, options);
    grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));

    grid.updateHeaderRow();
    grid.onCellChange.subscribe(function (e, args) {
        grid.dataView.updateItem(args.item.Id, args.item);
    });

    //    // Return the grid object so we can store it in a variable
    return grid;
}
function TimeEditor(args) {
    var $input, $wrapper;
    var defaultValue;
    var scope = this;

    this.init = function () {
        var $container = $("body");

        $wrapper = $("<DIV style='z-index:10000;position:absolute;background:white;padding:5px;border:3px solid gray; -moz-border-radius:10px; border-radius:10px;'/>")
          .appendTo($container);

        $input = $("<TEXTAREA hidefocus rows=5 style='backround:white;width:250px;height:80px;border:0;outline:0'>")
          .appendTo($wrapper);

        $("<DIV style='text-align:right'><BUTTON>Save</BUTTON><BUTTON>Cancel</BUTTON></DIV>")
          .appendTo($wrapper);

        $wrapper.find("button:first").bind("click", this.save);
        $wrapper.find("button:last").bind("click", this.cancel);
        $input.bind("keydown", this.handleKeyDown);

        scope.position(args.position);
        $input.focus().select();
    };

    this.handleKeyDown = function (e) {
        if (e.which == $.ui.keyCode.ENTER && e.ctrlKey) {
            scope.save();
        } else if (e.which == $.ui.keyCode.ESCAPE) {
            e.preventDefault();
            scope.cancel();
        } else if (e.which == $.ui.keyCode.TAB && e.shiftKey) {
            e.preventDefault();
            grid.navigatePrev();
        } else if (e.which == $.ui.keyCode.TAB) {
            e.preventDefault();
            grid.navigateNext();
        }
    };

    this.save = function () {
        args.commitChanges();
    };

    this.cancel = function () {
        $input.val(defaultValue);
        args.cancelChanges();
    };

    this.hide = function () {
        $wrapper.hide();
    };

    this.show = function () {
        $wrapper.show();
    };

    this.position = function (position) {
        $wrapper
          .css("top", position.top - 5)
          .css("left", position.left - 5)
    };

    this.destroy = function () {
        $wrapper.remove();
    };

    this.focus = function () {
        $input.focus();
    };

    this.loadValue = function (item) {
        $input.val(defaultValue = item[args.column.field]);
        $input.select();
    };

    this.serializeValue = function () {
        return $input.val();
    };

    this.applyValue = function (item, state) {
        item[args.column.field] = state;
    };

    this.isValueChanged = function () {
        return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
    };

    this.validate = function () {
        var value = $input.val().replace(/\s+/, "").replace(', ', ',');

        if (!value.match(/^\d{1,2}(:\d{2})?((AM)|(PM))-\d{1,2}(:\d{2})?((AM)|(PM))($|(,\d{1,2}(:\d{2})?((AM)|(PM))-\d{1,2}(:\d{2})?((AM)|(PM)))*$)/i)) {
            return false;
        }
        var msg = "";
        var timeEntries = value.split(',');
        $.each(timeEntries, function (i, entry) {
            //var entry = this;
            if (!entry.match(/-\d{1,2}(:\d{2})?((AM)|(PM))/i)) {
                msg = "Incorrect Format";
            } else {
                var fromTo = entry.split('-');
                var from = hourMinuteToMinutes(fromTo[0]);
                var to = hourMinuteToMinutes(fromTo[1]);
                if (from[0] == 0 || from[0] > 12 || to[0] == 0 || to[0] > 12)
                    msg = "The hour must be a number between 1 and 12";
                else if (from[2] >= to[2])
                    msg = "Start time must be earlier than end time!";
            }
        });
        function hourMinuteToMinutes(hourMinute) {
            var amPM = hourMinute.match(/am/i) ? "AM" : "PM";
            hourMinute = hourMinute.replace(/\s+(AM)|(PM)/i, "");
            hourMinute = hourMinute.split(':');
            hourMinute[0] = parseInt(hourMinute[0]);
            var _24hour = hourMinute[0];
            if (amPM == "PM")
                _24hour += 12;
            if (hourMinute[0]) {
                hourMinute[2] = hourMinute.length == 1
                    ? _24hour * 60
                    : parseInt(hourMinute[1]) + (_24hour * 60);

                return hourMinute;
            }
            return 0;
        }
        if (msg)
            return { valid: false, msg: msg };
        return {
            valid: true,
            msg: null
        };
    };

    this.init();
}
